<template>
  <a-modal
    v-model:visible="modalVisible"
    @ok="buildOrder"
    @cancel="handleCancel"
    :mask-closable="false"
    width="1200px"
    ok-text="创建采购订单"
  >
    <template #title> 明细列表 </template>
    <a-space direction="vertical" fill>
      <div>
        <a-table :columns="columns" :data="data" :pagination="false">
          <template #columns>
            <a-table-column :width="80" align="center">
              <template #title> 序号 </template>
              <template #tr> </template>
              <template #cell="{ rowIndex }">
                <div style="display: flex">
                  <div style="margin-left: 20px">
                    <span>{{ rowIndex + 1 }}</span>
                  </div>
                  <!-- <div
                    @click="addNewProduct(record, rowIndex)"
                    style="margin-left: 20px"
                  >
                    <icon-plus />
                  </div> -->
                </div>
              </template>
            </a-table-column>
            <a-table-column
              v-for="item in columns"
              :title="item.title"
              :data-index="item.code"
              :key="item.code"
              :width="200"
              align="center"
            >
              <!-- 数量 -->
              <template v-if="item.code === 'amount'" #cell="{ record }">
                <a-input-number
                  :min="1"
                  @change="amountChange(record)"
                  placeholder="请输入销售数量"
                  v-model="record.amount"
                  hide-button
                />
              </template>
              <!-- 供应商名称 -->
              <template
                v-else-if="item.code === 'SupplierId'"
                #cell="{ record, rowIndex }"
              >
                <a-input
                  v-model="record.supplierName"
                  hide-button
                  @click="SelectSup(record.number, rowIndex)"
                />
              </template>
              <!-- 指导单价 -->
              <template
                v-else-if="item.code === 'guidePrice'"
                #cell="{ record }"
              >
                <a-input-group>
                  <a-input-number
                    :min="1"
                    @change="saleMoneyChange(record)"
                    v-model="record.guidePrice"
                    hide-button
                  />
                  <a-select
                    default-value="人民币"
                    v-model="record.guidePriceUnit"
                    :options="['人民币', '美元', '港币']"
                  />
                </a-input-group>
              </template>
              <!-- 折扣 -->
              <template v-else-if="item.code === 'discount'" #cell="{ record }">
                <a-input-number
                  :min="1"
                  hide-button
                  v-model="record.discount"
                  @change="cgeDiscount(record)"
                >
                  <template #append> % </template>
                </a-input-number>
              </template>
              <!-- 合计 -->
              <template v-else-if="item.code === 'total'" #cell="{ record }">
                <a-input-group>
                  <a-input v-model="record.totalPrice" />
                  <a-select
                    default-value="人民币"
                    v-model="record.guidePriceUnit"
                    :options="['人民币', '美元', '港币']"
                  />
                </a-input-group>
              </template>
            </a-table-column>
            <!-- <a-table-column
              :width="200"
              fixed="right"
              title="操作"
              align="center"
              v-if="props.type === 1"
            >
              <template #title> 操作 </template>
              <template #cell="{ record }">
                <div>
                  <a-button type="text" @click="CreateOrder(record)"
                    >创建采购订单</a-button
                  >
                </div>
              </template>
            </a-table-column> -->
          </template>
        </a-table>
      </div>
    </a-space>
  </a-modal>
  <SelectSupplier
    v-if="SuppliermodalVisible"
    v-model:visible="SuppliermodalVisible"
    :code="supplierNumber"
    @awardedSupplier="awardedSupplier"
  />
</template>

<script lang="ts" setup>
  import { cloneDeep } from 'lodash';
  import { reactive, computed, watchEffect, onMounted, ref, watch } from 'vue';
  import { localGetUserInfo } from '@/utils/localStorage/account';
  import { getPurchaseProductNumber } from '@/api/buy-management/buy-material/index';
  import { postPurchaseAddByOrder } from '@/api/buy-management/buy-material/index';
  import { useRouter } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import { useBuyStore } from '@/store';
  import SelectSupplier from './select-supplier.vue';

  const store = useBuyStore();
  const router = useRouter();
  const SuppliermodalVisible = ref(false);
  const currentIndex = ref();
  const props = withDefaults(
    defineProps<{
      SeeDate: any;
      type: any;
      visible: boolean;
    }>(),
    {
      visible: false,
    }
  );

  //   // 表格配置
  //   const args = reactive({
  //     stripe: true,
  //     rowSelection: {
  //       type: 'checkbox',
  //       showCheckedAll: true,
  //       onlyCurrent: false,
  //     },
  //     scroll: {
  //       y: 500,
  //     },
  //     bordered: {
  //       headerCell: true,
  //     },
  //     rowKey: 'name', // 批量选择按钮 以合同名称来作为key
  //   });

  const columns = [
    {
      title: '物料编码',
      code: 'number',
    },
    {
      title: '物料名称',
      code: 'name',
    },
    {
      title: '型号规格',
      code: 'spec',
    },
    {
      title: '基本单位',
      code: 'basicName',
    },
    {
      title: '需求数量',
      code: 'amount',
    },
    {
      title: '关联申请单号',
      code: 'applyNumber',
    },
    {
      title: '供应商名称',
      code: 'SupplierId',
    },
    {
      title: '产品指导单价',
      code: 'guidePrice',
    },
    {
      title: '折扣',
      code: 'discount',
    },
    {
      title: '合计',
      code: 'total',
    },
  ];

  const emit = defineEmits(['update:visible', 'addRoleEmit']);

  // 判断用户是否显示弹出框
  const modalVisible = computed({
    get() {
      return props.visible;
    },
    set(visible: boolean) {
      emit('update:visible', visible);
    },
  });

  const data: any = ref([]);

  const getData = () => {
    data.value = props.SeeDate;
    data.value.forEach(async (item: any) => {
      const res = await getPurchaseProductNumber({ number: item.number });
      let markSupplier = res.filter((i: any) => i.mark === 1);
      if (!markSupplier.length) markSupplier = res;
      item.supplierName = markSupplier[0].supplierName || '';
      item.supplierId = markSupplier[0].supplierId || null;
      item.guidePrice = markSupplier[0].singlePrice || null;
      item.totalPrice = markSupplier[0].singlePrice * item.amount || null;
      item.guidePriceUnit = '人民币';
    });
  };

  const amountChange = (record: any) => {
    if (record.guidePrice !== undefined && record.amount !== undefined) {
      record.totalPrice = record.guidePrice * record.amount;
    } else record.totalPrice = 0;
  };

  // 修改销售单价价格
  const saleMoneyChange = (record: any) => {
    if (record.guidePrice !== undefined && record.amount !== undefined) {
      record.totalPrice = record.guidePrice * record.amount;
    } else record.totalPrice = 0;
  };

  const cgeDiscount = (record: any) => {
    if (record.discount) {
      saleMoneyChange(record);
      let msg = ref(0);
      msg.value = (100 - record.discount) / 100;
      const newMsg = record.guidePrice * record.amount;
      record.totalPrice = newMsg * msg.value;
    } else {
      saleMoneyChange(record);
    }
  };

  const supplierNumber = ref();
  const SelectSup = (code: string, index: number) => {
    supplierNumber.value = code;
    SuppliermodalVisible.value = true;
    currentIndex.value = index;
  };

  const awardedSupplier = (tatleDate: any) => {
    data.value.forEach((i: any, index: number) => {
      if (currentIndex.value === index) {
        i.supplierName = tatleDate[0].supplierName;
        i.supplierId = tatleDate[0].supplierId;
        i.guidePrice = tatleDate[0].singlePrice;
        i.discount = tatleDate[0].discount ? tatleDate[0].discount : 0;
        saleMoneyChange(i);
      }
    });
  };

  const CreateOrder = (record: any) => {};

  // const addNewProduct = (record: any, rowIndex: number) => {
  //   const NewObj = cloneDeep(record);
  //   NewObj.amount = 0;
  //   data.value.splice(rowIndex + 1, 0, NewObj);
  // };

  // 汇总创建采购订单
  const buildOrder = async () => {
    if (props.type === 1) {
      const { supplierId, supplierName, totalPrice, id } = data.value[0];
      if (supplierId) {
        store.CreateOrder = {
          supplierId,
          supplierName,
          totalPrice,
          Product: [{ ...data.value[0], planProductId: id }],
        };
        router.push({
          name: 'AddOrderPurchaseList',
        });
      } else {
        Message.error('请选择供应商');
      }
    } else {
      const msg = data.value.every(
        (item: any) => item.supplierId === data.value[0].supplierId
      );
      if (!msg) {
        Message.error('供应商不一致，无法创建订单');
      } else {
        let msg: any = ref({
          supplierId: data.value[0].supplierId,
          supplierName: data.value[0].supplierName,
          totalPrice: 0,
          Product: [],
        });
        data.value.forEach((item: any, index: number) => {
          msg.value.Product.push({
            ...item,
            planProductId: item.id,
          });
          delete item.id;
        });
        for (let i = 0; i < msg.value.Product.length; i += 1) {
          msg.value.totalPrice += msg.value.Product[i].totalPrice;
        }
        store.CreateOrder = msg.value;
        router.push({
          name: 'AddOrderPurchaseList',
        });
      }
    }
  };

  watchEffect(() => {
    if (props.visible) {
      data.value = [];
      getData();
    }
  });
</script>

<style scoped lang="less"></style>
